﻿/* ######################################## *\
 * ### Copyright (C) 2009 AJ Ravindiran ### *
\* ######################################## */
using System;
using System.Threading;

using AJRavindiran.Jolt.RuneScape.Models.Characters;
using AJRavindiran.Jolt.Utilities;

namespace AJRavindiran.Jolt.RuneScape.Workers
{
    /// <summary>
    /// Represents a worker.
    /// </summary>
    public class LoginWorker
    {
        #region Fields
        private Thread loginWorkerThread;
        #endregion Fields

        #region Constructors
        public LoginWorker()
        {
            Jolt.GetLog().WriteInfo("Constructing login worker...");

            // Initialize the worker thread, set the normal priority, and start it.
            this.loginWorkerThread = new Thread(new ThreadStart(Run));
            this.loginWorkerThread.Priority = ThreadPriority.Normal;
            this.loginWorkerThread.Name = "LoginWorkerThread";
        }
        #endregion Constructors

        #region Destructors
        #endregion Destructors

        #region Methods
        /// <summary>
        /// A thread which runs the login server processor every second.
        /// </summary>
        private void Run()
        {
            while (true)
            {
                if (RuneScape.GetLoginServer().GetQueuedCharacters().Count > 0)
                {
                    Character[] queuedCharactersArray = null;
                    RuneScape.GetLoginServer().GetQueuedCharacters().CopyTo(queuedCharactersArray);
                    foreach (Character c in queuedCharactersArray)
                    {
                        if (c.GetStatus().Online)
                            continue;
                        RuneScape.GetLoginServer().Process(c);
                        if (c.GetStatus().LoginStage == -1 || (DateTime.Now - c.GetStatus().LoginTime) >= TimeSpan.FromSeconds(15))
                        {
                            if (!c.GetStatus().Online)
                                RuneScape.GetCharacterManager().UnRegister(c);
                            RuneScape.GetLoginServer().GetQueuedCharacters().Remove(c);
                        }
                    }
                }

                try
                {
                    Thread.Sleep(1000);
                } 
                catch (Exception ex) 
                { 
                    Jolt.GetLog().WriteException(ex); 
                }
            }
        }

        /// <summary>
        /// Get accessor for the login worker thread.
        /// </summary>
        public Thread GetThread()
        {
            return this.loginWorkerThread;
        }
        #endregion Methods
    }
}
